<template>
    <div class="divBox">
        <el-card class="mt14">
            <el-button type="primary" size="small" @click="dialogVisible = true" class="mb20">添加轮播图</el-button>

            <!-- 轮播图列表区域 -->
            <div class="carousel-list">
                <div class="carousel-header">
                    <div class="header-item" style="width: 10%">ID</div>
                    <div class="header-item" style="width: 15%">轮播标题</div>
                    <div class="header-item" style="width: 10%">显示状态</div>
                    <div class="header-item" style="width: 20%">轮播图片</div>
                    <div class="header-item" style="width: 15%">创建时间</div>
                    <div class="header-item" style="width: 20%">操作</div>
                </div>

                <div class="carousel-items">
                    <div v-for="(item, index) in tableData.data" :key="item.mings_id" class="carousel-item">
                        <div class="item-cell" style="width: 10%">{{ item.mings_id }}</div>
                        <div class="item-cell" style="width: 15%">{{ item.title }}</div>
                        <div class="item-cell" style="width: 10%">
                            <el-switch v-model="item.is_show" :active-value="1" :inactive-value="0" :width="55"
                                active-text="显示" inactive-text="隐藏" @change="onchangeIsShow(item)" />
                        </div>
                        <div class="item-cell" style="width: 20%">
                            <div class="carousel-image-container">
                                <img :src="item.image_url || 'https://picsum.photos/300/150'" alt="轮播图预览"
                                    class="carousel-image">
                            </div>
                        </div>
                        <div class="item-cell" style="width: 15%">{{ item.create_time }}</div>
                        <div class="item-cell" style="width: 20%">
                            <el-button type="text" @click="editVisible(item.mings_id)" size="small"
                                class="mr10">编辑</el-button>
                            <el-button type="text" size="small"
                                @click="handleDelete(item.mings_id, index)">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="block">
                <el-pagination background :page-size="tableFrom.limit" :current-page="tableFrom.page"
                    layout="total, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange"
                    @current-change="pageChange" />
            </div>
        </el-card>

        <!-- 添加轮播图弹窗 -->
        <el-dialog title="添加轮播图" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false"
            @closed="resetForm">
            <el-form ref="bannerForm" :model="bannerForm" :rules="rules" label-width="100px" size="small">
                <el-form-item label="轮播标题" prop="title">
                    <el-input v-model="bannerForm.title" placeholder="请输入轮播标题" maxlength="50"
                        show-word-limit></el-input>
                </el-form-item>



                <el-form-item label="显示状态" prop="is_show">
                    <el-switch v-model="bannerForm.is_show" :active-value="1" :inactive-value="0" :width="55"
                        active-text="显示" inactive-text="隐藏"></el-switch>
                </el-form-item>
                <el-form-item label="轮播图片" prop="pic">
                    <div class="acea-row row-middle">
                        <div class="upLoadPicBox mr15" title="710*340px" @click="modalPicTap('1', 0)">
                            <div v-if="bannerForm.image_url" class="pictrue">
                                <img :src="bannerForm.image_url">
                            </div>
                            <div v-else class="upLoad">
                                <i class="iconfont iconjiahao" />
                            </div>
                        </div>
                        <div style="color: #ccc;font-size: 12px;">
                            建议尺寸710*340px
                            <el-popover placement="bottom" title="" min-width="200" trigger="hover">
                                <img :src="`${baseURL}/statics/system/topic94_01.jpg`" style="height:270px;" alt="">
                                <el-button type="text" slot="reference">查看示例</el-button>
                            </el-popover>
                        </div>
                    </div>
                </el-form-item>

                <!-- <el-form-item label="轮播链接" prop="link">
            <el-input
              v-model="bannerForm.link"
              placeholder="请输入轮播图跳转链接"
              maxlength="255"
            ></el-input>
          </el-form-item> -->

                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="bannerForm.sort" :min="0" :max="999" :step="1"
                        placeholder="数字越小越靠前"></el-input-number>
                </el-form-item>
            </el-form>

            <div slot="footer">
                <el-button size="small" @click="dialogVisible = false">取消</el-button>
                <el-button size="small" type="primary" @click="submitForm">
                    确认提交
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { bannerList, bannerChangeStatus, bannerDelete, bannerAdd, bannerInfo } from "@/api/mings";
import { formatDate } from "@/utils/validate";
import { roterPre } from '@/settings'
import SettingMer from '@/libs/settingMer'
export default {
    name: "BannerList",
    filters: {
        formatDate(time) {
            if (time !== 0) {
                let date = new Date(time * 1000);
                return formatDate(date, "yyyy-MM-dd hh:mm");
            }
        },
    },
    data() {
        return {
            baseURL: SettingMer.httpUrl || 'http://localhost:8080',
            loading: false,
            roterPre: roterPre,
            tableData: {
                data: [],
                total: 0,
            },
            tableFrom: {
                title: "",
                page: 1,
                limit: 15,
            },
            // 弹窗相关数据
            dialogVisible: false,
            fileList: [],
            bannerForm: {
                title: '',
                type: '',
                is_show: 1,
                image_url: '',
                link: '',
                sort: 0,
                mings_id:0
            },
            rules: {
                title: [
                    { required: true, message: '请输入轮播标题', trigger: 'blur' },
                    { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
                ],

                image_url: [
                    { required: true, message: '请上传轮播图片', trigger: 'change' }
                ]
            }
        };
    },
    computed: {
    },
    created() {
        this.getList('');
    },
    methods: {
        /**重置搜索表单 */
        searchReset() {
            if (this.$refs.searchForm) {
                this.$refs.searchForm.resetFields()
            }
            this.getList(1)
        },
        editVisible(mings_id) {
            this.dialogVisible = true
            bannerInfo(mings_id)
                .then(async (res) => {
                    this.bannerForm = res.data
                })
                .catch(({ message }) => {
                    this.$message.error(message)
                })
        },
        // 删除轮播图
        handleDelete(id, idx) {
            this.$modalSure('删除该轮播图').then(() => {
                bannerDelete(id)
                    .then(({ message }) => {
                        this.$message.success(message)
                        this.tableData.data.splice(idx, 1)
                        this.tableData.total--
                    })
                    .catch(({ message }) => {
                        this.$message.error(message)
                    })
            })
        },

        // 获取列表数据
        getList(num) {
            this.loading = true;
            this.tableFrom.page = num ? num : this.tableFrom.page;
            bannerList(this.tableFrom)
                .then(async (res) => {
                    this.tableData.data = res.data.list;
                    this.tableData.total = res.data.count;
                    this.loading = false;
                })
                .catch((res) => {
                    this.loading = false;
                    this.$message.error(res.message);
                });
        },
        // 分页切换
        pageChange(page) {
            this.tableFrom.page = page;
            this.getList('');
        },
        // 每页条数变化
        handleSizeChange(val) {
            this.tableFrom.limit = val;
            this.getList('');
        },
        // 修改显示状态
        onchangeIsShow(row) {
            bannerChangeStatus(row.mings_id, row.is_show)
                .then(async (res) => {
                    this.$message.success(res.message);
                    this.getList('');
                })
                .catch((res) => {
                    this.$message.error(res.message);
                    this.getList('');
                });
        },

        // 弹窗表单相关方法
        // 重置表单
        resetForm() {
            if (this.$refs.bannerForm) {
                this.$refs.bannerForm.resetFields()
            }
            this.fileList = []
            this.bannerForm = {
                title: '',
                type: '',
                is_show: 1,
                image_url: '',
                link: '',
                sort: 0
            }
        },
        // 图片上传前校验
        beforeUpload(file) {
            const isImage = file.type.indexOf('image/') === 0
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isImage) {
                this.$message.error('只能上传图片格式文件!')
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
                return false
            }
            return true
        },
        // 图片上传成功处理
        handleUploadSuccess(response) {
            if (response.code === 200) {
                this.bannerForm.image_url = response.data.url
                this.fileList = [{ url: response.data.url }]
                this.$message.success('图片上传成功')
            } else {
                this.$message.error(response.message || '图片上传失败')
            }
        },
        // 图片上传失败处理
        handleUploadError() {
            this.$message.error('图片上传失败，请重试')
        },
        // 提交添加表单
        submitForm() {
            this.$refs.bannerForm.validate(async (valid) => {
                if (valid) {
                    try {
                        const { message } = await bannerAdd(this.bannerForm)
                        this.$message.success(message)
                        this.dialogVisible = false
                        // 重新获取列表数据
                        this.getList(1)
                    } catch (error) {
                        this.$message.error(error.message || '添加失败')
                    }
                }
            })
        },
        modalPicTap(tit, num, i) {
            const _this = this;
            this.$modalUpload(function (img) {
                _this.bannerForm.image_url = img[0];
            }, tit);
        },
    },
};
</script>

<style scoped lang="scss">
/* 轮播图列表样式 */
.carousel-list {
    margin-bottom: 20px;
    overflow-x: auto;

    .carousel-header {
        display: flex;
        background-color: #f5f7fa;
        border-radius: 4px 4px 0 0;
        padding: 10px 0;
        font-weight: bold;

        .header-item {
            padding: 0 10px;
            text-align: center;
        }
    }

    .carousel-items {
        .carousel-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #ebeef5;
            transition: background-color 0.2s;

            &:hover {
                background-color: #f9fafc;
            }

            .item-cell {
                padding: 0 10px;
                text-align: center;

                .carousel-image-container {
                    width: 100%;
                    height: 80px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    overflow: hidden;
                    border-radius: 4px;
                    background-color: #f5f7fa;

                    .carousel-image {
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: cover;
                    }
                }
            }
        }
    }
}

/* 基础样式 */
.divBox {
    padding: 15px;
}

.selCard {
    background: #fff;
    margin-bottom: 15px;
    border-radius: 4px;
}

.selWidth {
    width: 180px;
}

.mt14 {
    margin-top: 14px;
}

.mb20 {
    margin-bottom: 20px;
}

.mr10 {
    margin-right: 10px;
}

.block {
    padding: 20px;
    text-align: right;
}

/* 上传组件样式 */
.el-upload__tip {
    margin-top: 5px !important;
    font-size: 12px;
}
</style>